package com.bluezone.dec.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.CacheConstant;
import com.bluezone.dec.common.SystemConstant;
import com.bluezone.dec.configuration.AppConfig;
import com.bluezone.dec.system.service.EnterpriseService;
import com.bluezone.dec.system.service.ExhaustGasAndWaterStatisticsService;
import com.bluezone.dec.system.service.MonitorAlarmService;
import com.bluezone.dec.system.vo.ComplaintWayVo;
import com.bluezone.dec.system.vo.EnterpriseEnvironmentVo;
import com.bluezone.dec.system.vo.GasAndWaterVo;
import com.bluezone.dec.utils.TimeTransferUtils;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Auther: motb
 * @Date: 2018/11/14 11:38
 * @Description: 企业环保情况统计
 */
@Service
public class ExhaustGasAndWaterStatisticsServiceImpl implements ExhaustGasAndWaterStatisticsService {

    @Autowired
    private MonitorAlarmService monitorAlarmService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /***
     * 废气、废水、环保投诉
     * @return
     */
    @Override
    public Map<String, Object> statisticsCount() {

        if (Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.WATER_GAS_COMPLAINT))) {

            Map<String, Object> map = new HashMap<>();
            // 废气、废水
            List<JSONObject> resultArray = monitorAlarmService.getGasAndWaterAlarmStatistics().toJavaList(JSONObject.class);
            for (JSONObject jsonObject : resultArray) {
                String code = jsonObject.getString("code");
                String waterCode = appConfig.getWaterCode();
                String gasCode = appConfig.getGasCode();
                boolean flag = !Strings.isNullOrEmpty(code);
                if (flag && code.equals(waterCode)) {
                    map.put("water", jsonObject.getIntValue("count"));
                }
                if (flag && code.equals(gasCode)) {
                    map.put("gas", jsonObject.getIntValue("count"));
                }
            }

            List<JSONObject> enterpriseList = enterpriseService.getEnterpriseInfo(CacheConstant.ENTERPRISE_ENVIRONMENT).toJavaList(JSONObject.class);
            List<JSONObject> environmentalLetterList = new ArrayList<>();

            for (JSONObject jsonObject : enterpriseList) {
                JSONArray tmpMap = Optional.ofNullable(jsonObject.getJSONObject(SystemConstant.ENVIRONMENTAL))
                        .map(m -> m.getJSONObject(SystemConstant.ENVIRONMENT_BASE_INFO))
                        .map(m -> m.getJSONArray(SystemConstant.ENVIRONMENTAL_LETTER_LIST))
                        .orElse(new JSONArray());

                environmentalLetterList.addAll(tmpMap.toJavaList(JSONObject.class));
            }

            environmentalLetterList = environmentalLetterList.stream()
                    .filter(m -> m.getString("complaintDate").substring(0, 4).equals(TimeTransferUtils.getSystemCurrentYear()))
                    .collect(Collectors.toList());

            map.put("monitor", environmentalLetterList.size());

            /* 设置废气、废水、环保投诉缓存过期时间 */
            redisTemplate.opsForValue().set(CacheConstant.WATER_GAS_COMPLAINT,
                    JSON.toJSONString(map),
                    appConfig.getChartDataCacheTime(),
                    TimeUnit.SECONDS);
            return map;
        } else {
            String waterGasCompaint = redisTemplate.opsForValue().get(CacheConstant.WATER_GAS_COMPLAINT);
            return JSON.parseObject(waterGasCompaint, Map.class);
        }
    }

    /***
     * 企业废水指标报警情况
     * @return
     */
    @Override
    public List gasAndWaterGenerate(String code) {

        if (Strings.isNullOrEmpty(redisTemplate.opsForValue().get(code))) {

            List<Map<String, Object>> resultList = new ArrayList<>();
            Map<String, Object> itemMap = new HashMap<>();
            Map<String, List<GasAndWaterVo>> monitorMap = monitorAlarmService.getGasAndWaterAlarmStatus();

            List<GasAndWaterVo> gasAndWaterVos = Optional.ofNullable(monitorMap)
                    .map(m -> m.get(code)).orElse(null);

            itemMap.put("rectName", Optional.ofNullable(gasAndWaterVos)
                    .map(m -> m.get(0).getTypeName()).orElse(null));

            List<Map<String, Object>> entList = new ArrayList<>();

            if (null != gasAndWaterVos) {
                gasAndWaterVos.forEach(m -> {
                    Map<String, Object> tmp = new HashMap<>();
                    tmp.put(SystemConstant.NAME, m.getEntName());
                    tmp.put(SystemConstant.VALUE, m.getCount());
                    entList.add(tmp);
                });
            }

            itemMap.put("ent", entList);
            resultList.add(itemMap);

            /* 设置企业废水指标报警情况缓存过期时间 */
            redisTemplate.opsForValue().set(code,
                    JSON.toJSONString(resultList),
                    appConfig.getChartDataCacheTime(),
                    TimeUnit.SECONDS);

            return resultList;
        } else {
            String result = redisTemplate.opsForValue().get(code);
            return JSONArray.parseArray(result, Map.class);
        }
    }

    /**
     * 企业投诉及投入情况
     *
     * @return
     */
    @Override
    public Map<String, Object> superviseInvestment() {

        if (Strings.isNullOrEmpty(redisTemplate.opsForValue().get(CacheConstant.COMPLAINT_INVEST))) {

            Map<String, Object> resultMap = new HashMap<>();
            JSONArray enterpriseList = enterpriseService.getEnterpriseInfo(CacheConstant.ENTERPRISE_ENVIRONMENT);
            List<EnterpriseEnvironmentVo> environmentVos = new ArrayList<>();

            if (!StringUtils.isEmpty(enterpriseList)) {

                for (int i = 0; i < enterpriseList.size(); i++) {

                    EnterpriseEnvironmentVo environmentVo = new EnterpriseEnvironmentVo();
                    JSONObject jsonObject = enterpriseList.getJSONObject(i);

                    if (Optional.ofNullable(jsonObject).isPresent()) {

                        environmentVo.setCreditCode(jsonObject.getString(SystemConstant.ENTERPRISE_CODE));
                        environmentVo.setName(jsonObject.getString(SystemConstant.NAME));

                        environmentVo.setEnvironmentalProtectionInvestment(Optional
                                .ofNullable(jsonObject.getJSONObject("environmental"))
                                .map(m -> m.getJSONObject("environmentBaseInfo"))
                                .map(m -> m.getJSONObject("environmentalProtectionBasicInfo"))
                                .map(m -> m.getDouble("environmentalProtectionInvestment")
                                ).orElse(0d));

                        environmentVo.setEnvironmentalLetterList(Optional
                                .ofNullable(jsonObject.getJSONObject("environmental"))
                                .map(m -> m.getJSONObject("environmentBaseInfo"))
                                .map(m -> m.getJSONArray("environmentalLetterList").toJavaList(ComplaintWayVo.class))
                                .orElse(new ArrayList<>()));

                        environmentVos.add(environmentVo);
                    }
                }

            }

            Collections.sort(environmentVos, Comparator.comparing(EnterpriseEnvironmentVo::getName).reversed());
            List<Map<String, Object>> superviseList = new ArrayList<>();
            List<Map<String, Object>> investmentList = new ArrayList<>();

            environmentVos.forEach(e -> {
                Map<String, Object> supervise = new HashMap<>();
                Map<String, Object> investment = new HashMap<>();
                supervise.put(SystemConstant.NAME, e.getName());
                supervise.put(SystemConstant.VALUE, e.getEnvironmentalLetterList().size());
                superviseList.add(supervise);
                investment.put(SystemConstant.NAME, e.getName());
                investment.put(SystemConstant.VALUE, e.getEnvironmentalProtectionInvestment());
                investmentList.add(investment);
            });

            resultMap.put("supervise", superviseList);
            resultMap.put("investment", investmentList);

            /* 设置企业投诉及投入情况缓存过期时间 */
            redisTemplate.opsForValue().set(CacheConstant.COMPLAINT_INVEST,
                    JSON.toJSONString(resultMap),
                    appConfig.getChartDataCacheTime(),
                    TimeUnit.SECONDS);

            return resultMap;
        } else {
            String result = redisTemplate.opsForValue().get(CacheConstant.COMPLAINT_INVEST);
            return JSON.parseObject(result, Map.class);
        }
    }
}
